package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyZhongXinHua;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeZhongXinHua;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 众鑫花信息流全 https://www.showdoc.com.cn/2598837328200790/11558628943857168 密码：zhjf
 *
 * @author WJB
 */
@ApiPlan(productId = "405", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatZhongXinHuaPhoneMd5Convert implements ApiPlatformPhoneMaskConvertHandler {

    public static final String KEY = "rcb4p16wb9zj85q2";
    private static final String CHANNEL_CODE = "CHN1754627181830";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        ApiPlatDataExchangeZhongXinHua data = new ApiPlatDataExchangeZhongXinHua();
        data.setMobilePrefix8(apiDataExchangeParameter.getPhoneMask());
        data.setUserName("默认姓名");
        //  年龄
        data.setAge(Integer.valueOf(apiDataExchangeParameter.getAge()));
        //  性别
        Integer sexChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .end(1);
        data.setSex(sexChoose);
        //  所属省份（例如 上海市,浙江省）
        data.setProvinceName(apiDataExchangeParameter.getProvinceName());
        //  城市
        data.setCityName(apiDataExchangeParameter.getCity().replace("市", ""));
        // 芝麻分
        String newSesameSeedChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "4", "700分以上")
                .when(apiDataExchangeParameter.getSesameCredit(), "3", "650-699分")
                .when(apiDataExchangeParameter.getSesameCredit(), "2", "600-649分")
                .when(apiDataExchangeParameter.getSesameCredit(), "1", "600分以下")
                .end("600分以下");
        data.setSesameSeed(newSesameSeedChoose);
        // 花呗额度
        String huabeiChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getHbLimit(), "1", "无花呗")
                .when(apiDataExchangeParameter.getHbLimit(), "2", "有花呗")
                .when(apiDataExchangeParameter.getHbLimit(), "3", "有花呗")
                .when(apiDataExchangeParameter.getHbLimit(), "4", "有花呗")
                .when(apiDataExchangeParameter.getHbLimit(), "5", "有花呗")
                .end("无花呗");
        data.setHuabei(huabeiChoose);
        // 白条额度
        String whiteStripeChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getBtLimit(), "1", "无白条")
                .when(apiDataExchangeParameter.getBtLimit(), "2", "有白条")
                .when(apiDataExchangeParameter.getBtLimit(), "3", "有白条")
                .when(apiDataExchangeParameter.getBtLimit(), "4", "有白条")
                .when(apiDataExchangeParameter.getBtLimit(), "5", "有白条")
                .end("无白条");
        data.setWhiteStripe(whiteStripeChoose);
        // 逾期情况
        String overdueSituationChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", "无逾期")
                .when(apiDataExchangeParameter.getOverdue(), "2", "有逾期")
                .when(apiDataExchangeParameter.getOverdue(), "3", "无逾期")
                .end("无逾期");
        data.setOverdueSituation(overdueSituationChoose);
        // 贷款金额
        String loanAmountChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", "5万以下")
                .when(apiDataExchangeParameter.getLoanAmount(), "2", "5万到20万")
                .when(apiDataExchangeParameter.getLoanAmount(), "3", "5万到20万")
                .when(apiDataExchangeParameter.getLoanAmount(), "4", "20万以上")
                .end("5万以下");
        data.setLoanLimit(loanAmountChoose);
        //  学历
        String educationAttainment = ChooseEq.create()
                .when(apiDataExchangeParameter.getEducationAttainment(), "1", "高中及以下")
                .when(apiDataExchangeParameter.getEducationAttainment(), "2", "中专")
                .when(apiDataExchangeParameter.getEducationAttainment(), "3", "高中及以下")
                .when(apiDataExchangeParameter.getEducationAttainment(), "4", "大专")
                .when(apiDataExchangeParameter.getEducationAttainment(), "5", "本科及以上")
                .when(apiDataExchangeParameter.getEducationAttainment(), "6", "本科及以上")
                .end("高中及以下");
        data.setEducation(educationAttainment);
        // 社保缴纳情况
        String socialSecurityChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", "无社保")
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", "有社保")
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", "有社保")
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", "有社保")
                .end("无社保");
        data.setSocialSecurity(socialSecurityChoose);
        // 信用卡额度
        String creditCardChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", "无信用卡")
                .when(apiDataExchangeParameter.getCreditLimit(), "2", "有信用卡")
                .when(apiDataExchangeParameter.getCreditLimit(), "3", "有信用卡")
                .when(apiDataExchangeParameter.getCreditLimit(), "4", "有信用卡")
                .when(apiDataExchangeParameter.getCreditLimit(), "5", "有信用卡")
                .when(apiDataExchangeParameter.getCreditLimit(), "6", "有信用卡")
                .end("无信用卡");
        data.setCreditCard(creditCardChoose);
        // 职业类型
        String occupationChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", "上班族")
                .when(apiDataExchangeParameter.getCareer(), "2", "自由职业")
                .when(apiDataExchangeParameter.getCareer(), "3", "企业主")
                .when(apiDataExchangeParameter.getCareer(), "4", "上班族")
                .when(apiDataExchangeParameter.getCareer(), "5", "自由职业")
                .end("上班族");
        data.setOccupation(occupationChoose);
        //  公积金
        String accumulation = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", "无公积金")
                .when(apiDataExchangeParameter.getProvidentFund(), "2", "有公积金")
                .when(apiDataExchangeParameter.getProvidentFund(), "3", "有公积金")
                .when(apiDataExchangeParameter.getProvidentFund(), "4", "有公积金")
                .end("无公积金");
        data.setAccumulation(accumulation);
        // 保险缴纳年限
        String insuranceChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", "无保险")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", "有保险")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", "有保险")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", "有保险")
                .end("无保险");
        data.setInsurance(insuranceChoose);
        // 车辆情况
        String carChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", "无车")
                .when(apiDataExchangeParameter.getCarInfo(), "2", "有车")
                .when(apiDataExchangeParameter.getCarInfo(), "3", "有车")
                .when(apiDataExchangeParameter.getCarInfo(), "4", "有车")
                .end("无车");
        data.setCar(carChoose);
        // 房产情况
        String houseChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", "无房")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", "有房")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", "有房")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", "有房")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", "有房")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", "有房")
                .end("无房");
        data.setHouse(houseChoose);
        // 用户IP地址
        if (ValidParam.isEmpty(apiDataExchangeParameter.getIp())) {
            data.setRegIp("127.0.0.1");
        } else {
            data.setRegIp(apiDataExchangeParameter.getIp());
        }
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("data", dataStr);
            newMap.put("requestNo", apiDataExchangeParameter.getReqId());
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        ApiPlatApplyZhongXinHua data = new ApiPlatApplyZhongXinHua();
        data.setMobile(apiApplyParameter.getPhone());
        data.setUserName(apiApplyParameter.getUserName());
        //  年龄
        data.setAge(Integer.valueOf(apiApplyParameter.getAge()));
        //  性别
        Integer sexChoose = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", 1)
                .when(apiApplyParameter.getSex(), "1", 2)
                .end(1);
        data.setSex(sexChoose);
        //  所属省份（例如 上海市,浙江省）
        data.setProvinceName(apiApplyParameter.getProvinceName());
        //  城市
        data.setCityName(apiApplyParameter.getCity().replace("市", ""));
        // 芝麻分
        String newSesameSeedChoose = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "4", "700分以上")
                .when(apiApplyParameter.getSesameCredit(), "3", "650-699分")
                .when(apiApplyParameter.getSesameCredit(), "2", "600-649分")
                .when(apiApplyParameter.getSesameCredit(), "1", "600分以下")
                .end("600分以下");
        data.setSesameSeed(newSesameSeedChoose);
        // 花呗额度
        String huabeiChoose = ChooseEq.create()
                .when(apiApplyParameter.getHbLimit(), "1", "无花呗")
                .when(apiApplyParameter.getHbLimit(), "2", "有花呗")
                .when(apiApplyParameter.getHbLimit(), "3", "有花呗")
                .when(apiApplyParameter.getHbLimit(), "4", "有花呗")
                .when(apiApplyParameter.getHbLimit(), "5", "有花呗")
                .end("无花呗");
        data.setHuabei(huabeiChoose);
        // 白条额度
        String whiteStripeChoose = ChooseEq.create()
                .when(apiApplyParameter.getBtLimit(), "1", "无白条")
                .when(apiApplyParameter.getBtLimit(), "2", "有白条")
                .when(apiApplyParameter.getBtLimit(), "3", "有白条")
                .when(apiApplyParameter.getBtLimit(), "4", "有白条")
                .when(apiApplyParameter.getBtLimit(), "5", "有白条")
                .end("无白条");
        data.setWhiteStripe(whiteStripeChoose);
        // 逾期情况
        String overdueSituationChoose = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", "无逾期")
                .when(apiApplyParameter.getOverdue(), "2", "有逾期")
                .when(apiApplyParameter.getOverdue(), "3", "无逾期")
                .end("无逾期");
        data.setOverdueSituation(overdueSituationChoose);
        // 贷款金额
        String loanAmountChoose = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", "5万以下")
                .when(apiApplyParameter.getLoanAmount(), "2", "5万到20万")
                .when(apiApplyParameter.getLoanAmount(), "3", "5万到20万")
                .when(apiApplyParameter.getLoanAmount(), "4", "20万以上")
                .end("5万以下");
        data.setLoanLimit(loanAmountChoose);
        //  学历
        String educationAttainment = ChooseEq.create()
                .when(apiApplyParameter.getEducationAttainment(), "1", "高中及以下")
                .when(apiApplyParameter.getEducationAttainment(), "2", "中专")
                .when(apiApplyParameter.getEducationAttainment(), "3", "高中及以下")
                .when(apiApplyParameter.getEducationAttainment(), "4", "大专")
                .when(apiApplyParameter.getEducationAttainment(), "5", "本科及以上")
                .when(apiApplyParameter.getEducationAttainment(), "6", "本科及以上")
                .end("高中及以下");
        data.setEducation(educationAttainment);
        // 社保缴纳情况
        String socialSecurityChoose = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", "无社保")
                .when(apiApplyParameter.getSocialSecurity(), "2", "有社保")
                .when(apiApplyParameter.getSocialSecurity(), "3", "有社保")
                .when(apiApplyParameter.getSocialSecurity(), "4", "有社保")
                .end("无社保");
        data.setSocialSecurity(socialSecurityChoose);
        // 信用卡额度
        String creditCardChoose = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", "无信用卡")
                .when(apiApplyParameter.getCreditLimit(), "2", "有信用卡")
                .when(apiApplyParameter.getCreditLimit(), "3", "有信用卡")
                .when(apiApplyParameter.getCreditLimit(), "4", "有信用卡")
                .when(apiApplyParameter.getCreditLimit(), "5", "有信用卡")
                .when(apiApplyParameter.getCreditLimit(), "6", "有信用卡")
                .end("无信用卡");
        data.setCreditCard(creditCardChoose);
        // 职业类型
        String occupationChoose = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", "上班族")
                .when(apiApplyParameter.getCareer(), "2", "自由职业")
                .when(apiApplyParameter.getCareer(), "3", "企业主")
                .when(apiApplyParameter.getCareer(), "4", "上班族")
                .when(apiApplyParameter.getCareer(), "5", "自由职业")
                .end("上班族");
        data.setOccupation(occupationChoose);
        //  公积金
        String accumulation = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", "无公积金")
                .when(apiApplyParameter.getProvidentFund(), "2", "有公积金")
                .when(apiApplyParameter.getProvidentFund(), "3", "有公积金")
                .when(apiApplyParameter.getProvidentFund(), "4", "有公积金")
                .end("无公积金");
        data.setAccumulation(accumulation);
        // 保险缴纳年限
        String insuranceChoose = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", "无保险")
                .when(apiApplyParameter.getInsurancePolicy(), "2", "有保险")
                .when(apiApplyParameter.getInsurancePolicy(), "3", "有保险")
                .when(apiApplyParameter.getInsurancePolicy(), "4", "有保险")
                .end("无保险");
        data.setInsurance(insuranceChoose);
        // 车辆情况
        String carChoose = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", "无车")
                .when(apiApplyParameter.getCarInfo(), "2", "有车")
                .when(apiApplyParameter.getCarInfo(), "3", "有车")
                .when(apiApplyParameter.getCarInfo(), "4", "有车")
                .end("无车");
        data.setCar(carChoose);
        // 房产情况
        String houseChoose = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", "无房")
                .when(apiApplyParameter.getRealEstateInfo(), "2", "有房")
                .when(apiApplyParameter.getRealEstateInfo(), "3", "有房")
                .when(apiApplyParameter.getRealEstateInfo(), "4", "有房")
                .when(apiApplyParameter.getRealEstateInfo(), "5", "有房")
                .when(apiApplyParameter.getRealEstateInfo(), "6", "有房")
                .end("无房");
        data.setHouse(houseChoose);
        // 用户IP地址
        if (ValidParam.isEmpty(apiApplyParameter.getIp())) {
            data.setRegIp("127.0.0.1");
        } else {
            data.setRegIp(apiApplyParameter.getIp());
        }
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("data", dataStr);
            newMap.put("requestNo", apiApplyParameter.getReqId());
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        // 获取响应数据
        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();

        //  获取携带参数
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("merchantName");
        //  用户协议
        List<ApiProtocol> protocolList = new ArrayList<>();
        //  获取协议
        JSONObject listProtocolResult = resData.getJSONObject("agreementsList");
        ApiProtocol protocol = new ApiProtocol();
        protocol.setProtocolUrl(listProtocolResult.getString("register"));
        protocolList.add(protocol);
        //  获取手机号掩码
        List<String> listPhoneMd5 = new ArrayList<>();
        JSONArray jsonArray = resData.getJSONArray("mobileMd5List");
        IteratorUtils.array(jsonArray, (item, index) -> {
            String phoneMd5  = jsonArray.getString(index);
            listPhoneMd5.add(phoneMd5);
        });

        RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();
        result.setProductName(companyName);
        result.setProtocolList(protocolList);
        result.setListPhoneMd5(listPhoneMd5);
        result.setDisplayName(companyName);
        result.setPrice(price);
        listRespPlatformPhoneMaskDataExchange.add(result);

        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }
}
